<template>
  <view class="flex-col">

    <view :class="boole?'bottom115':''">
      <!--基础信息-->
      <basic-info v-model="detailForm"/>

      <!--装饰信息-->
      <decoration-info v-model="detailForm" :boole="boole" ref="refDecorationInfo"/>

      <!--精品装饰说明-->
      <view class="item-wrap" style="margin-bottom: 0">
        <view class="lineBottom10">
          <uni-section title="精品装饰说明" type="line"/>
        </view>

        <view style="margin: 8rpx 20rpx 30rpx 20rpx">
          <uni-forms ref="detailForm" :model="detailForm" labelWidth="0">
            <view style="display: flex;justify-content: flex-start;align-items: center;margin-bottom: 20rpx">
              <text style="font-size: 40rpx;font-weight: 700">费用合计:</text>
              <text style="font-size: 40rpx;font-weight:700">{{ `￥${detailForm.price}` }}</text>
              <button v-if="boole" class="uni-button add-button" size="mini" type="primary" @click="addDecoration">
                添加
              </button>
            </view>

            <uni-table ref="table" border stripe emptyText="暂无更多数据">
              <uni-tr>
                <uni-th width="100" align="center" v-if="boole">操作</uni-th>
                <uni-th width="130" align="center">项目</uni-th>
                <uni-th width="120" align="center">预算金额</uni-th>
                <uni-th width="150" align="center">
                  <text style="color: red">*</text>
                  实际金额
                </uni-th>
              </uni-tr>
              <uni-tr v-for="(item, index) in detailForm.proList" :key="index">
                <uni-td v-if="boole ">
                  <view v-if="item.decorateType === '2'"
                        style="display: flex;justify-content: center;align-items: center">
                    <button class="uni-button" size="mini" @click="delDecoration(item, index )" type="warn">删除
                    </button>
                  </view>

                </uni-td>
                <uni-td align="center">
                  <uni-easyinput v-if="boole && item.decorateType === '2'" v-model="item.decorateName"/>
                  <text v-else>{{ item.decorateName || ''}}</text>
                </uni-td>

                <uni-td align="center">

                  <uni-easyinput v-if="boole && item.decorateType === '2'"
                                 v-model="item.budgetPrice"
                                 @clear="clear(item,'budgetPrice')"
                                 @blur="blurTable(item,'budgetPrice')"/>
                  <text v-else>{{ item.budgetPrice || ''}}</text>
                </uni-td>

                <uni-td align="center">
                  <uni-forms-item :name="'proList.'+index+'.actualPrice'"
                                  :rules="[{
                                    required:item.decorateType !== '2',
                                    errorMessage: '请输入实际金额', validateTrigger: 'blur'
                                 }]">
                    <uni-easyinput v-if="boole"
                                   v-model="item.actualPrice"
                                   @clear="clear(item,'actualPrice')"
                                   @blur="blurTable(item,'actualPrice')"/>
                    <text v-else>{{ item.actualPrice || ''}}</text>
                  </uni-forms-item>
                </uni-td>
              </uni-tr>
            </uni-table>

          </uni-forms>
        </view>
      </view>

      <!--审批流程-->
      <exam-flow v-if="flowId" :instanceId="flowId"/>
    </view>



    <view class="button-container" v-if="boole">
      <button class="btn-item" @click="submit">提 交</button>
    </view>

  </view>
</template>

<script>
import {
  getDecorateInfoByWorkId,
  getByCarId,
  addDecorate,
} from "@/api/decoration";
import basicInfo from "./components/basicInfo.vue";
import decorationInfo from "./components/decorationInfo.vue";

export default {
  name: "add",
  components: {basicInfo, decorationInfo},
  computed: {},
  watch: {},
  data() {
    return {
      boole: false,
      flowId: null,
      detailForm: {
        workId: '',
        businessDataId: "",
        expectEndTime: "",
        expectStartTime: "",
        price: "",
        supplierId: "",
        supplierName: "",
        proList: [],
        createTime: '',
        contractType: '',
        workOrderStatus: "",
        remainingTotalBudget: "",
        totalBudget: "",
        actualStartTime: "",
        actualEndTime: "",
        payType: "",
        feedbackAdvancePayment: "",
        photoUrl: "",//装饰完成照片
        voucherUrl: "",//结算单上传
        view: "",//装饰意见反馈
        remark:"",
      },
      opObj: {}
    };
  },
  onLoad(op) {
    let title = "";
    this.flowId = op?.flowId;
    this.opObj = op
    if (op?.type === "edit") {
      this.getByCarId(op?.id);
      title = "新增装饰工单";
      this.boole = true;
      if(op?.workOrderStatus === '5'){
        this.getDecorate(op?.id);
      }
    }
    if (op?.type === "view") {
      this.getDecorate(op?.id);
      title = "装饰工单详情";
      this.boole = false;
    }
    this.detailForm.carId = op?.carId;
    uni.setNavigationBarTitle({
      title,
    });
  },
  mounted() {
  },
  methods: {
    getByCarId(id) {
      getByCarId(id).then((res) => {
        for (const key in res.data) {
          this.$set(this.detailForm, key, res.data[key]);
        }
        this.detailForm.price = 0;
        let arr = JSON.parse(JSON.stringify(res.data.decorateProList));
        this.$set(this.detailForm, "proList", arr);
      });
    },

    // 详情回显
    getDecorate(id) {
      getDecorateInfoByWorkId(id).then((res) => {
        if (res.code === 200) {
          this.isForm = true;
          this.detailForm = res.data;
          this.$set(this.detailForm, "decorateProList", res.data.proList);
        }
      });
    },

    //添加表格
    addDecoration() {
      let obj = {
        id: "",
        decorateId: "",
        decorateName: "",
        budgetPrice: "",
        actualPrice: "",
        remark: "",
        disabled: false,
        decorateType: "2",
      };
      this.detailForm.proList.push(obj);
    },

    //删除表格
    delDecoration(row, key) {
      this.detailForm.proList.splice(key, 1);
      this.handlePrice();
    },

    blurTable(row, field) {
      let _value
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/
      if (row[field]) {
        if (msg.test(Number(row[field]))) {
          if (Number(row[field]) >= 0) {
            _value = row[field].toString().match(/^\d+(?:\.\d{0,2})?/)[0];
            row[field] = _value
          } else {
            row[field] = ""
          }
        } else {
          row[field] = ""
        }
      }
      this.handlePrice()
    },

    clear(row, field){
      row[field] = ""
      this.handlePrice()
    },

    handlePrice() {
      let total = 0n;
      for (let item of this.detailForm.proList) {
        let num = (Number(item.actualPrice) * 100).toFixed(0)
        const bigIntPrice = BigInt(Number(num));
        total += bigIntPrice
      }
      this.$set(this.detailForm, 'price', Number(total) / 100)
      //this.$forceUpdate()
    },

    async submit() {
      try {
        let effectPromises = [
          this.$refs.refDecorationInfo.handleEffect(),
          this.handleEffect()
        ]
        await Promise.all(effectPromises);
        uni.showLoading();
        this.detailForm.workId = this.opObj?.id
        this.detailForm.carId = this.opObj?.carId
        this.detailForm.workOrderStatus = "2"
        let res = await addDecorate(this.detailForm);
        if (res.code === 200) {
          uni.$emit("refBackList", true);
          this.$modal.msgSuccess("提交成功");
          setTimeout(() => {
            this.$tab.navigateBack();
          }, 1000);
        }
      } catch (error) {
        if (typeof error === "string") {
          this.$nextTick(() => {
            uni.pageScrollTo({
              selector: error,
            });
          });
        } else {
          console.error(error);
        }
      } finally {
        setTimeout(()=>{uni.hideLoading()},1000)
      }
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.detailForm.validate().then(res => {
          resolve();
        }).catch(err => {
          reject(err);
        })
      });
    },
  },
};
</script>

<style scoped lang=""></style>


